<template>
  <view class="w-[358px] mx-auto color-[#999] mt-2">
    <!-- 患者信息卡片 -->
    <view class="bg-white rounded-lg shadow-xl p-3 pt-4 text-[14px] flex flex-col gap-2">
      <!-- 患者基本信息 -->
      <view class="flex justify-between items-center flex-wrap gap-2">
        <view class="flex items-center">
          <text class="name font-bold text-[16px]">{{nurseUser.name}}</text>
          <!-- <text class="heart-icon relative left-[4px] top-[-10px] text-[12px]">💎💎💎</text> -->
        </view>

        <view class="guardian-info flex items-center gap-1">
          <text class="guardian font-bold text-blue-500 text-[14px]" @tap="onTapGuardian">{{curFamily?.name || goodsStore.family?.name || '选择家庭成员'}}</text>
          <text class="text-[12px] text-gray-600">(重大病史)</text>
          <text class="text-[12px] text-gray-600">12</text>
        </view>

        <text class="gender-age text-[14px]">{{(other as any)?.sex==='1'?'男':'女'}} {{(other as any)?.age || 20}}{{(other as any)?.ageUnit || '岁'}}</text>
        <text class="relation text-[14px]">关系：{{(other as any)?.relationName|| '-'}}</text>
        <!-- 调试信息 -->
        <!-- <text class="text-xs text-red-500">调试: {{ nurseUser.nurseUserFamilyList?.length || 0 }}个家庭成员</text> -->
      </view>

      <view class="flex gap-8 items-center">
        <text class="text-[14px]">{{ nurseUser.idcard || '-' }}</text>
        <text class="text-[14px]">7710000000001</text>
      </view>

      <!-- 两列布局 -->
      <view class="flex gap-2 relative">
        <image
          :src="obj?.goods?.imagePath"
          mode="aspectFill" class="w-[80px] h-[80px] rounded-lg bg-[#eee]" />
        <view class="flex flex-col gap-1 flex-1">
          <text class="text-[16px] font-bold">{{ obj?.goods?.bill_name }}</text>
          <text class="text-[14px]">{{obj?.goods?.name}}</text>
          <text class="text-[14px]">服务时长：{{obj?.duration}}{{ serviceUnit }}</text>
        </view>
        <button class="absolute right-4 bottom-0 text-[12px]">
          收藏
        </button>
      </view>

      <view class="flex items-center">
        <image class="w-[16px] h-[16px] mr-1" mode="aspectFit" :src="ico"></image>
        <text class="text-[14px]">一站式整合型居家医疗照护服务</text>
      </view>
      <view class="flex items-center gap-[8rpx] flex-nowrap overflow-x-auto">
        <view class="px-[16rpx] py-[6rpx] rounded-[12rpx] bg-[#e8f5e9] flex-shrink-0">
          <text class="text-[24rpx] text-[#059669] font-medium">护士集团</text>
        </view>
        <view class="px-[16rpx] py-[6rpx] rounded-[12rpx] bg-[#e8f5e9] flex-shrink-0">
          <text class="text-[24rpx] text-[#059669] font-medium">健康管家</text>
        </view>
        <view class="px-[16rpx] py-[6rpx] rounded-[12rpx] bg-[#e8f5e9] flex-shrink-0">
          <text class="text-[24rpx] text-[#059669] font-medium">健康档案</text>
        </view>
        <view class="px-[16rpx] py-[6rpx] rounded-[12rpx] bg-[#e8f5e9] flex-shrink-0">
          <text class="text-[24rpx] text-[#059669] font-medium">三重评估</text>
        </view>
        <view class="px-[16rpx] py-[6rpx] rounded-[12rpx] bg-[#e8f5e9] flex-shrink-0">
          <text class="text-[24rpx] text-[#059669] font-medium">双人入户</text>
        </view>
      </view>
    </view>


  </view>

  <!-- 家庭成员选择器 -->
  <nut-popup v-model:visible="showFamilyPicker" position="bottom">
    <nut-picker 
      :columns="familyOptions" 
      :default-value="curFamily?.id ? [curFamily.id] : []"
      title="选择家庭成员"
      @confirm="confirmFamilyMember"  
      @cancel="showFamilyPicker=false"
    />
  </nut-popup>
</template>

<script lang="ts" setup>
// import { useAuthStore } from '@/store';
import { ref, computed, onMounted, watch } from 'vue';
import { storeToRefs } from 'pinia';
import ico from '@/assets/ico/logo.png'
import { useAuthStore, useGoodsStore } from '@/store';
import { getNurseUserFamilyList } from '@/service/api/nurse_user';
// import { service_unit } from '@/utils/dict';
import { getDict } from '@/service/api/dict';

const serviceUnit = ref('小时');

const goodsStore = useGoodsStore();

const props = defineProps({
  obj: {
    type: Object,
    required: true
  }
})

const { nurseUser, curFamily } = storeToRefs(useAuthStore());
const authStore = useAuthStore();
const techNum = ref(0.02)

// 家庭成员选择相关
const showFamilyPicker = ref(false);
const selectedFamilyIndex = ref(0);
const familyPickerValue = ref([0]);

// 初始化家庭数据
const initFamilyData = async () => {
  try {
    // 如果已经有家庭数据，直接使用
    if (nurseUser.value.nurseUserFamilyList && nurseUser.value.nurseUserFamilyList.length > 0) {
      updateFamilyData(nurseUser.value.nurseUserFamilyList);
      return;
    }
    
    // 如果没有家庭数据，从API获取
    // if (nurseUser.value.id) {
    //   // 从API获取家庭数据，用户ID
    //   const { error, success } = await getNurseUserFamilyList(nurseUser.value.id);
    //   // API返回结果
      
    //   if (!error && success?.records) {
    //     // 更新store中的家庭数据
    //     nurseUser.value.nurseUserFamilyList = success.records;
    //     // 更新家庭数据 (records)
    //     updateFamilyData(success.records);
    //   } else if (!error && Array.isArray(success)) {
    //     // 如果返回的是直接数组
    //     nurseUser.value.nurseUserFamilyList = success;
    //     // 更新家庭数据 (array)
    //     updateFamilyData(success);
    //   } else {
    //     // 没有获取到家庭数据
    //   }
    // } else {
    //   // 用户ID不存在，无法获取家庭数据
    // }
  } catch (error) {
    // 获取家庭成员数据失败
  }
};

// 更新家庭数据的通用方法
const updateFamilyData = (familyList: any[]) => {
  if (familyList && familyList.length > 0) {
    // 检查是否已经有选中的家庭成员
    let selectedFamily = curFamily.value;
    
    // 如果没有选中的家庭成员，或者选中的家庭成员不在当前列表中，则选择第一个
    if (!selectedFamily || !familyList.find(f => f.id === selectedFamily?.id)) {
      selectedFamily = familyList[0];
      authStore.setCurFamily(selectedFamily);
      // 设置默认选中的家庭成员
    }
    
    // 更新选中的索引
    const index = familyList.findIndex(f => f.id === selectedFamily?.id);
    if (index >= 0) {
      selectedFamilyIndex.value = index;
      familyPickerValue.value = [index];
    }
  }
};


// 家庭成员选项
const familyOptions = computed(() => {
  const familyList = nurseUser.value?.nurseUserFamilyList || [];
  return familyList.map((member: any) => ({
    ...member,
    text: member.name,
    value: member.id
  }));
});

// 点击选择家庭成员
const onTapGuardian = () => {
  if (familyOptions.value.length > 0) {
    showFamilyPicker.value = true;
  }
}

// 确认选择家庭成员
const confirmFamilyMember = ({ selectedValue, selectedOptions }: { selectedValue: any[], selectedOptions: any[] }) => {
  const selectedFamily = selectedOptions[0];
  
  if (selectedFamily) {
    // 保存选中的家庭成员到 curFamily
    authStore.setCurFamily(selectedFamily);
    
    // 更新选中的索引
    const familyList = nurseUser.value?.nurseUserFamilyList || [];
    const index = familyList.findIndex(f => f.id === selectedFamily.id);
    if (index >= 0) {
      selectedFamilyIndex.value = index;
      familyPickerValue.value = [index];
    }
    
    // 更新 goodsStore.family
    goodsStore.family = selectedFamily;
  }
  
  showFamilyPicker.value = false;
};

// 当前选中的家庭成员
const other = computed(() => {
  // 优先使用 curFamily，如果没有则使用索引方式
  if (curFamily.value) {
    return curFamily.value;
  }
  
  // 备用方案：使用索引方式
  const familyList = nurseUser.value?.nurseUserFamilyList || [];
  
  if (familyList.length > 0 && selectedFamilyIndex.value < familyList.length) {
    const selectedMember = familyList[selectedFamilyIndex.value] || {};
    return selectedMember;
  }
  
  return {};
})

// 监听家庭成员列表变化
watch(
  () => nurseUser.value.nurseUserFamilyList,
  newVal => {
    if (newVal && newVal.length > 0) {
      updateFamilyData(newVal);
    }
  },
  { deep: true }
);

// 监听当前选中的家庭成员变化
watch(
  () => curFamily.value,
  newVal => {
    if (newVal) {
      // 更新 goodsStore.family
      goodsStore.family = newVal;
    }
  },
  { deep: true }
);

// 组件挂载时初始化
onMounted(() => {
  initFamilyData();

  getDict('service_unit').then((res:any) => {
    // serviceUnit.value = res;
    // console.log('serviceUnit ------', res, props.obj);
    res.forEach((item: any) => {
      if(item.itemValue == props.obj?.unit){
        serviceUnit.value = item.itemText;
      }
    });
  });
});

defineExpose({
  getPrice() {
    return props.obj?.price + techNum.value
  }
})
</script>

<style lang="scss">
.nut-radio__label{
  font-size: 20rpx;
}
.nut-radio {
  margin-bottom: 0px !important;
  padding-bottom: 0px!important;
}
</style>
